package top.jnaw.jee.platform.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.util.List;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.base.BaseKcglUser;
import top.jnaw.jee.utils.Html2Test;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Models;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class KcglUser extends BaseKcglUser<KcglUser> {

  public static final KcglUser dao = new KcglUser().dao();

  public static ModelResult check(int kid, String openid, String status) {
    ModelResult result = new ModelResult(Result.kModelSaveError);

//    List<KcglUser> list = dao
//        .find("SELECT * from kcgl_user where kid=? AND openid = ?", kid,
//            openid);
    KcglUser k = getByOpenid(kid, openid);
    boolean r = false;
    if (null != k) {
      k.setStatus(status);
      r = k.update();
    } else {
      KcglUser ku = new KcglUser();
      ku.setKid(kid);
      ku.setOpenid(openid);
      ku.setStatus(status);
      r = ku.save();
    }
    if (r) {
      result.setResult(Result.kSuccess);
    }
    return result;
  }

  public static KcglUser getByOpenid(int kid, String openid) {
    return dao
        .findFirst("SELECT * from kcgl_user where kid= ? AND openid = ?", kid,
            openid);
  }

  public static String getStatusByOpenid(int kid, String openid) {
    KcglUser ku = dao
        .findFirst("SELECT * from kcgl_user where kid= ? AND openid = ?", kid,
            openid);
    String status = "";
    if (null != ku) {
      status = ku.getStatus();
    }
    return status;

  }

  public static JSONObject list(int page, int size, String keyWord) {

    String sec = Db.getSql("sign-list-sec");
    String exp = Db.getSql("sign-list-exp");
    if (StrKit.notBlank(keyWord)) {
      exp +=
          "\n" + "AND (kc.title like concat('%','" + keyWord
              + "','%') or  wuser.name like concat('%','" + keyWord
              + "','%') or  wuser.mobile like concat('%','" + keyWord + "','%'))";
    }
    exp += " order by ku.create_time desc ";
    Page<Record> pages = Db.paginate(page, size, sec, exp);
    return Models.compressPage(pages);
  }

}
